#!/bin/bash

# SkyWalking Java Agent 下载脚本
# 用于下载和配置 SkyWalking Java Agent

set -e

# 配置
SKYWALKING_VERSION="9.1.0"
DOWNLOAD_URL="https://archive.apache.org/dist/skywalking/java-agent/${SKYWALKING_VERSION}/apache-skywalking-java-agent-${SKYWALKING_VERSION}.tgz"
AGENT_DIR="skywalking-agent"
BACKUP_MIRROR="https://dlcdn.apache.org/skywalking/java-agent/${SKYWALKING_VERSION}/apache-skywalking-java-agent-${SKYWALKING_VERSION}.tgz"

echo "=========================================="
echo "SkyWalking Java Agent 下载工具"
echo "版本: ${SKYWALKING_VERSION}"
echo "=========================================="

# 检查是否已经存在
if [ -d "${AGENT_DIR}" ]; then
    echo "警告: ${AGENT_DIR} 目录已存在"
    read -p "是否要删除并重新下载? (y/n): " confirm
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
        echo "删除旧的 agent 目录..."
        rm -rf "${AGENT_DIR}"
    else
        echo "取消操作"
        exit 0
    fi
fi

# 下载 agent
echo "正在下载 SkyWalking Java Agent (约 30MB)..."
echo "下载地址: ${DOWNLOAD_URL}"

if curl -L --fail --progress-bar -o skywalking-agent.tgz "${DOWNLOAD_URL}"; then
    # 检查文件大小
    FILE_SIZE=$(ls -lh skywalking-agent.tgz | awk '{print $5}')
    echo "下载完成! 文件大小: ${FILE_SIZE}"
    
    # 验证是否是有效的 tar.gz 文件
    if ! file skywalking-agent.tgz | grep -q "gzip compressed"; then
        echo "错误: 下载的文件格式不正确"
        rm -f skywalking-agent.tgz
        exit 1
    fi
else
    echo ""
    echo "从主镜像下载失败，尝试备用镜像..."
    if curl -L --fail --progress-bar -o skywalking-agent.tgz "${BACKUP_MIRROR}"; then
        FILE_SIZE=$(ls -lh skywalking-agent.tgz | awk '{print $5}')
        echo "从备用镜像下载成功! 文件大小: ${FILE_SIZE}"
    else
        echo ""
        echo "❌ 自动下载失败"
        echo ""
        echo "请手动下载 SkyWalking Java Agent："
        echo "1. 访问: https://archive.apache.org/dist/skywalking/java-agent/${SKYWALKING_VERSION}/"
        echo "2. 下载: apache-skywalking-java-agent-${SKYWALKING_VERSION}.tgz"
        echo "3. 解压到项目根目录，重命名为 skywalking-agent"
        echo ""
        exit 1
    fi
fi

# 解压
echo "正在解压..."
tar -xzf skywalking-agent.tgz
rm skywalking-agent.tgz

# 重命名目录
if [ -d "skywalking-agent" ]; then
    echo "Agent 已就绪!"
else
    # 某些版本可能解压出不同的目录名
    mv apache-skywalking-java-agent-* skywalking-agent 2>/dev/null || true
fi

# 配置 agent
echo "正在配置 agent..."
cat > skywalking-agent/config/agent.config << EOF
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# The service name in UI
agent.service_name=\${SW_AGENT_NAME:springboot-apm-demo}

# Backend service addresses.
collector.backend_service=\${SW_AGENT_COLLECTOR_BACKEND_SERVICES:10.10.10.125:11800}

# Logging level
logging.level=\${SW_LOGGING_LEVEL:INFO}

# Logging file name
logging.file_name=\${SW_LOGGING_FILE_NAME:skywalking-api.log}

# Logging output
logging.output=\${SW_LOGGING_OUTPUT:FILE}

# Logging max file size
logging.max_file_size=\${SW_LOGGING_MAX_FILE_SIZE:10485760}

# Sample N out of X
agent.sample_n_per_3_secs=\${SW_AGENT_SAMPLE:-1}

# Authentication
# agent.authentication=\${SW_AGENT_AUTHENTICATION:}

# The max number of spans in a single segment
agent.span_limit_per_segment=\${SW_AGENT_SPAN_LIMIT:150}

# Ignore suffix of entry span
agent.ignore_suffix=\${SW_AGENT_IGNORE_SUFFIX:.jpg,.jpeg,.js,.css,.png,.bmp,.gif,.ico,.mp3,.mp4,.html,.svg}

# If true, skywalking agent will save all instrumented classes files in /debugging folder.
agent.is_cache_enhanced_class=\${SW_AGENT_CACHE_CLASS:false}

# The instrumented classes cache file size
agent.class_cache_mode=\${SW_AGENT_CLASS_CACHE_MODE:MEMORY}
EOF

echo ""
echo "=========================================="
echo "安装完成!"
echo "=========================================="
echo ""
echo "Agent 位置: $(pwd)/skywalking-agent"
echo ""
echo "使用方法："
echo ""
echo "1. 使用脚本启动（推荐）："
echo "   ./scripts/start-with-skywalking.sh"
echo ""
echo "2. 手动启动："
echo "   java -javaagent:$(pwd)/skywalking-agent/skywalking-agent.jar \\"
echo "        -Dskywalking.agent.service_name=springboot-apm-demo \\"
echo "        -Dskywalking.collector.backend_service=10.10.10.125:11800 \\"
echo "        -jar target/springboot-apm-demo.jar"
echo ""
echo "3. Maven 启动："
echo "   ./scripts/run-with-skywalking.sh"
echo ""

# 创建启动脚本
echo "正在创建启动脚本..."
cat > scripts/start-with-skywalking.sh << 'EOF'
#!/bin/bash

# 带 SkyWalking Agent 的启动脚本

set -e

# 配置
SERVICE_NAME="springboot-apm-demo"
SKYWALKING_BACKEND="10.10.10.125:11800"
AGENT_PATH="skywalking-agent/skywalking-agent.jar"
JAR_FILE="target/springboot-apm-demo.jar"

echo "=========================================="
echo "启动 Spring Boot 应用（带 SkyWalking）"
echo "=========================================="

# 检查 agent 是否存在
if [ ! -f "${AGENT_PATH}" ]; then
    echo "错误: SkyWalking agent 未找到"
    echo "请先运行: ./scripts/download-skywalking-agent.sh"
    exit 1
fi

# 检查 jar 文件是否存在
if [ ! -f "${JAR_FILE}" ]; then
    echo "错误: JAR 文件未找到"
    echo "请先运行: mvn clean package"
    exit 1
fi

# 启动应用
echo "正在启动应用..."
echo "Service Name: ${SERVICE_NAME}"
echo "SkyWalking Backend: ${SKYWALKING_BACKEND}"
echo ""

java -javaagent:${AGENT_PATH} \
     -Dskywalking.agent.service_name=${SERVICE_NAME} \
     -Dskywalking.collector.backend_service=${SKYWALKING_BACKEND} \
     -jar ${JAR_FILE}
EOF

chmod +x scripts/start-with-skywalking.sh

echo ""
echo "启动脚本已创建: scripts/start-with-skywalking.sh"
echo ""

